<template>
  <div class="course-browse-container">
    <div class="header">
      <h1>课程中心</h1>
      <p>发现并学习您感兴趣的课程</p>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="search-filter-section">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索课程..."
            clearable
            @keyup.enter="searchCourses"
          >
            <template #append>
              <el-button :icon="Search" @click="searchCourses" />
            </template>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-select
            v-model="selectedCategory"
            placeholder="选择分类"
            clearable
            @change="filterByCategory"
          >
            <el-option
              v-for="category in categories"
              :key="category.name"
              :label="category.name"
              :value="category.name"
            />
          </el-select>
        </el-col>
      </el-row>
    </div>

    <!-- 课程列表 -->
    <div class="course-list">
      <el-row :gutter="20">
        <el-col
          v-for="course in courses"
          :key="course.id"
          :span="8"
          class="course-card-col"
        >
          <el-card class="course-card" shadow="hover">
            <div class="course-cover">
              <img
                v-if="course.coverImage"
                :src="resolveImageUrl(course.coverImage)"
                :alt="course.title"
                class="cover-image"
                @error="handleImageError"
              />
              <div v-else class="default-cover">
                <el-icon><Collection /></el-icon>
              </div>
            </div>
            <div class="course-info">
              <h3 class="course-title">{{ course.title }}</h3>
              <p class="course-description">{{ course.description }}</p>
              <div class="course-meta">
                <el-tag
                  :type="getDifficultyTagType(course.difficultyLevel)"
                  size="small"
                >
                  {{ getDifficultyText(course.difficultyLevel) }}
                </el-tag>
                <span class="duration">
                  <el-icon><Clock /></el-icon>
                  {{ formatDuration(course.estimatedDuration) }}
                </span>
              </div>
              <div class="course-actions">
                <el-button
                  type="primary"
                  @click="viewCourseDetail(course.id)"
                >
                  查看详情
                </el-button>
                <template v-if="getEnrollmentStatus(course.id)">
                  <el-button
                    v-if="getEnrollmentStatus(course.id) === 'PENDING'"
                    type="warning"
                    disabled
                  >
                    审查中
                  </el-button>
                  <el-button
                    v-else-if="getEnrollmentStatus(course.id) === 'APPROVED'"
                    @click="continueLearning(course.id)"
                  >
                    继续学习
                  </el-button>
                  <el-button
                    v-else-if="getEnrollmentStatus(course.id) === 'COMPLETED'"
                    type="success"
                    disabled
                  >
                    已完成
                  </el-button>
                  <el-button
                    v-else
                    @click="enrollCourseInList(course.id)"
                  >
                    报名学习
                  </el-button>
                </template>
                <el-button
                  v-else
                  @click="enrollCourseInList(course.id)"
                >
                  报名学习
                </el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50]"
          :total="totalCourses"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  Search,
  Collection,
  Clock
} from '@element-plus/icons-vue'
import request from '../../utils/request'

// 路由
const router = useRouter()

// 数据
const courses = ref([])
const categories = ref([])
const subcategories = ref([])
const searchKeyword = ref('')
const selectedCategory = ref('')
const selectedSubcategory = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const totalCourses = ref(0)
const userEnrollments = ref([])

// 获取课程列表
const fetchCourses = async () => {
  try {
    const response = await request.get('/api/study/courses/published', {
      params: {
        page: currentPage.value - 1,
        size: pageSize.value,
        category: selectedCategory.value,
        subcategory: selectedSubcategory.value,
        keyword: searchKeyword.value
      }
    })

    courses.value = response.data.content
    totalCourses.value = response.data.totalElements

    // 获取用户报名信息
    fetchUserEnrollments()
  } catch (error) {
    ElMessage.error('获取课程列表失败')
  }
}

// 获取分类列表
const fetchCategories = async () => {
  try {
    const response = await request.get('/api/study/courses/categories')
    categories.value = response.data
  } catch (error) {
    ElMessage.error('获取分类列表失败')
  }
}

// 根据分类获取子分类
const fetchSubcategories = async (category: string) => {
  if (!category) {
    subcategories.value = []
    return
  }

  try {
    const response = await request.get('/api/study/courses/subcategories', {
      params: { category }
    })
    subcategories.value = response.data
  } catch (error) {
    ElMessage.error('获取子分类列表失败')
  }
}

// 获取用户报名信息
const fetchUserEnrollments = async () => {
  try {
    const response = await request.get('/api/study/courses/enrollments/all')
    userEnrollments.value = response.data.content || []
  } catch (error) {
    // 用户可能未登录，忽略错误
    userEnrollments.value = []
  }
}

// 课程列表页面的报名函数
const enrollCourseInList = async (courseId: number) => {
  try {
    const response = await request.post(`/api/study/courses/${courseId}/enroll`)

    if (response.data.success) {
      ElMessage.success('报名申请已提交，等待课程创建者审批')
      // 刷新报名信息
      fetchUserEnrollments()
    } else {
      ElMessage.error(response.data.message || '报名申请失败')
    }
  } catch (error) {
    console.error('报名课程失败:', error)
    ElMessage.error('报名课程失败')
  }
}

// 搜索课程
const searchCourses = () => {
  currentPage.value = 1
  fetchCourses()
}

// 按分类筛选
const filterByCategory = (category: string) => {
  selectedSubcategory.value = ''
  fetchSubcategories(category)
  currentPage.value = 1
  fetchCourses()
}

// 按子分类筛选
const filterBySubcategory = () => {
  currentPage.value = 1
  fetchCourses()
}

// 查看课程详情
const viewCourseDetail = (courseId: number) => {
  router.push(`/study/courses/${courseId}`)
}

// 继续学习
const continueLearning = (courseId: number) => {
  router.push(`/study/learning/${courseId}`)
}

// 报名课程
const enrollCourse = async (courseId: number) => {
  try {
    await request.post(`/api/study/enrollments/courses/${courseId}`)
    ElMessage.success('课程报名成功')
    fetchUserEnrollments()
  } catch (error) {
    ElMessage.error('课程报名失败')
  }
}

// 检查是否已报名课程
const isEnrolled = (courseId: number) => {
  const enrollment = userEnrollments.value.find(
    (enrollment: any) => enrollment.courseId === courseId
  )
  return enrollment ? enrollment.status === 'APPROVED' : false
}

// 获取用户的报名状态
const getEnrollmentStatus = (courseId: number) => {
  const enrollment = userEnrollments.value.find(
    (enrollment: any) => enrollment.courseId === courseId
  )
  return enrollment ? enrollment.status : null
}


// 分页相关方法
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  fetchCourses()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchCourses()
}

// 工具方法
const getDifficultyTagType = (level: string) => {
  switch (level) {
    case 'BEGINNER':
      return 'success'
    case 'INTERMEDIATE':
      return 'warning'
    case 'ADVANCED':
      return 'danger'
    default:
      return 'info'
  }
}

const getDifficultyText = (level: string) => {
  switch (level) {
    case 'BEGINNER':
      return '初级'
    case 'INTERMEDIATE':
      return '中级'
    case 'ADVANCED':
      return '高级'
    default:
      return '未知'
  }
}

const formatDuration = (minutes: number) => {
  if (!minutes) return '未知时长'
  return `${minutes}分钟`
}

// 解析图片URL，确保使用正确的完整路径
const resolveImageUrl = (imageUrl: string) => {
  if (!imageUrl) return ''

  // 如果已经是完整URL，则直接返回
  if (imageUrl.startsWith('http://') || imageUrl.startsWith('https://')) {
    return imageUrl
  }

  // 如果是相对路径，添加API基础URL
  const apiBaseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080'
  if (imageUrl.startsWith('/')) {
    return `${apiBaseUrl}${imageUrl}`
  }

  // 默认返回原URL
  return imageUrl
}

// 处理图片加载错误
const handleImageError = (event: Event) => {
  // 可以在这里添加错误处理逻辑，比如显示默认图片
  console.warn('图片加载失败:', event)
}

// 监听路由变化
const route = useRoute()
watch(
  () => route.name,
  (newName, oldName) => {
    if (newName === 'CourseBrowse') {
      // 当返回到课程浏览页面时，重新加载数据
      fetchCourses()
      fetchUserEnrollments()
    }
  }
)

// 组件挂载时获取数据
onMounted(() => {
  fetchCourses()
  fetchCategories()
})
</script>

<style scoped>
.course-browse-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100%;
}

.header {
  margin-bottom: 30px;
}

.header h1 {
  color: #303133;
  margin-bottom: 10px;
}

.header p {
  color: #606266;
  margin: 0;
}

.search-filter-section {
  margin-bottom: 30px;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.course-list {
  margin-bottom: 30px;
}

.course-card-col {
  margin-bottom: 20px;
}

.course-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.course-cover {
  height: 150px;
  overflow: hidden;
  border-radius: 4px;
  margin-bottom: 15px;
}

.cover-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.default-cover {
  width: 100%;
  height: 100%;
  background-color: #f0f2f5;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  font-size: 2em;
}

.course-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.course-title {
  font-size: 16px;
  font-weight: bold;
  margin: 0 0 10px 0;
  color: #303133;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.course-description {
  font-size: 14px;
  color: #606266;
  margin: 0 0 15px 0;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.course-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.duration {
  font-size: 12px;
  color: #909399;
  display: flex;
  align-items: center;
  gap: 4px;
}

.course-actions {
  display: flex;
  gap: 10px;
  margin-top: auto;
}

.course-actions .el-button {
  flex: 1;
  font-size: 12px;
  padding: 8px 12px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}
</style>
